<?php

namespace App\Services\Admin\Sponsor;

use App\Exceptions\SponsorException;
use App\Models\Applet\Sponsor\UserSlaughterRecordsModel;
use App\Models\Applet\User\UserIntegralRecordsModel;
use App\Models\Applet\User\UserSponsorModel;
use Exception;
use Illuminate\Support\Facades\DB;

class SlaughterService extends BaseSponsorService
{
    /**
     * 宰杀申请列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        $total = $this->getUserSlaughterRecordsModel()->total($params);
        // 查询宰杀申请列表
        $slaughterRecords = $this->getUserSlaughterRecordsModel()->list($params, [
            'user_slaughter_records.id', 'user_slaughter_records.user_id', 'user_sponsor_id',
            'user_slaughter_records.type', 'user_slaughter_records.status', 'user_slaughter_records.created_at',
            'users.nickname', 'users.phone'
        ]);

        // 查询用户认养记录列表
        $userSponsorIds = array_column($slaughterRecords, 'user_sponsor_id');
        $userSponsorList = $this->getUserSponsorModel()->getItemsByIds($userSponsorIds, [
            'id', 'name',
        ]);
        $userSponsorListMap = array_column($userSponsorList, null, 'id');

        // 宰杀申请列表发放积分map
        $slaughterRecordIds = array_column($slaughterRecords, 'id');
        $slaughterIntegralRecords = $this->getSlaughterIntegralRecordsModel()->getItemByUserSlaughterRecordIds($slaughterRecordIds, [
            'slaughter_integral_records.id', 'user_slaughter_records_id', 'quantity'
        ]);
        $slaughterIntegralRecordsMap = array_column($slaughterIntegralRecords, null, 'user_slaughter_records_id');

        // 宰杀申请列表寄回快递 slaughter_send_back_records
        $slaughterSendBackRecords = $this->getSlaughterSendBackRecordsModel()->getItemByUserSlaughterRecordIds($slaughterRecordIds, [
            'slaughter_send_back_records.id', 'user_slaughter_records_id', 'express_no'
        ]);
        $slaughterSendBackRecordsMap = array_column($slaughterSendBackRecords, null, 'user_slaughter_records_id');

        $list = [];
        foreach ($slaughterRecords as $item) {
            $list[] = [
                'id' => $item['id'],
                'userSponsorId' => $item['user_sponsor_id'],
                'nickname' => $item['nickname'] ?? '',
                'phone' => $item['phone'] ?? '',
                'sponsorName' => $userSponsorListMap[$item['user_sponsor_id']]['name'] ?? '',
                'type' => $item['type'],
                'integral' => $slaughterIntegralRecordsMap[$item['id']]['quantity'] ?? 0,
                'expressNo' => $slaughterSendBackRecordsMap[$item['id']]['express_no'] ?? '',
                'status' => $item['status'],
                'created_at' => $item['created_at'],
            ];
        }

        return [
            'list' => $list,
            'total' => $total,
        ];
    }

    /**
     * 宰杀申请详情
     *
     * @param array $params
     * @return array
     * @throws SponsorException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询审批记录
        $slaughterRecords = $this->getUserSlaughterRecordsModel()->getItemById($params['id'], [
            'id', 'type', 'status', 'remark'
        ]);
        if (empty($slaughterRecords)) {
            throw new SponsorException('用户申请记录不存在', SponsorException::CODE_5001);
        }

        // 查询收货地址
        $addressInfo = [];
        $userSlaughterAddressInfo = $this->getUserSlaughterAddressModel()->getItemByUserSlaughterId($slaughterRecords['id'], [
            'id', 'receive_name', 'receive_tel', 'area_info', 'address', 'province_id', 'city_id', 'region_id'
        ]);
        if (!empty($userSlaughterAddressInfo)) {
            // 查询地区名称
            $areaIds = [$userSlaughterAddressInfo['province_id'], $userSlaughterAddressInfo['city_id'], $userSlaughterAddressInfo['region_id']];
            $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
            $areaListMap = array_column($areaList, 'name', 'code');
            $addressInfo = [
                'id' => $userSlaughterAddressInfo['id'],
                'receiveName' => $userSlaughterAddressInfo['receive_name'],
                'receiveTel' => $userSlaughterAddressInfo['receive_tel'],
                'areaInfo' => $userSlaughterAddressInfo['area_info'],
                'address' => $userSlaughterAddressInfo['address'],
                'province' => $areaListMap[$userSlaughterAddressInfo['province_id']],
                'city' => $areaListMap[$userSlaughterAddressInfo['city_id']],
                'region' => $areaListMap[$userSlaughterAddressInfo['region_id']],
            ];
        }

        // 寄回记录
        $sendBackInfo = [];
        if ($slaughterRecords['type'] == UserSlaughterRecordsModel::TYPE_SEND_BACK) {
            $sendBackRecords = $this->getSlaughterSendBackRecordsModel()->getItemByUserSlaughterRecordsId($slaughterRecords['id'], [
                'id', 'user_slaughter_records_id', 'slaughter_express_id'
            ]);
            if (!empty($sendBackRecords)) {
                $sendBackRecords = $this->getSlaughterExpressModel()->getItemById($sendBackRecords['slaughter_express_id'], [
                    'id', 'express_company_code', 'express_no', 'phone'
                ]);

                // 查询物流信息
                $expressList = $this->getExpressApi()->query($sendBackRecords['express_company_code'], $sendBackRecords['express_no'], $sendBackRecords['phone']);

                $sendBackInfo = [
                    'id' => $sendBackRecords['id'],
                    'expressNo' => $sendBackRecords['express_no'],
                    'expressList' => $expressList,
                ];
            }
        }

        // 发放积分记录
        $integralInfo = [];
        if ($slaughterRecords['type'] == UserSlaughterRecordsModel::TYPE_RECYCLE) {
            $integral = $this->getSlaughterIntegralRecordsModel()->getItemByUserSlaughterRecordsId($slaughterRecords['id'], [
                'id', 'user_slaughter_records_id', 'user_integral_records_id'
            ]);
            if (!empty($integral)) {
                $integralInfo = $this->getUserIntegralRecordsModel()->getItemsByIds($integral['user_integral_records_id'], [
                    'id', 'type', 'quantity', 'remark'
                ]);
            }
        }

        return [
            'id' => $slaughterRecords['id'],
            'type' => $slaughterRecords['type'],
            'status' => $slaughterRecords['status'],
            'remark' => $slaughterRecords['remark'],
            'sendBackInfo' => !empty($sendBackInfo) ? $sendBackInfo : null,
            'integralInfo' => !empty($integralInfo) ? $integralInfo : null,
            'addressInfo' => $addressInfo,
        ];
    }

    /**
     * 审批
     * @param array $params
     * @return void
     * @throws SponsorException
     * @throws Exception
     */
    public function examine(array $params)
    {
        // 查询审批记录
        $slaughterRecords = $this->getUserSlaughterRecordsModel()->getItemById($params['id'], [
            'id', 'user_sponsor_id'
        ]);
        if (empty($slaughterRecords)) {
            throw new SponsorException('用户申请记录不存在', SponsorException::CODE_5001);
        }

        DB::transaction(function () use ($params, $slaughterRecords) {

            $this->getUserSlaughterRecordsModel()->updateItemById($params['id'], [
                'id' => $params['id'],
                'status' => $params['status'],
                'remark' => $params['remark'] ?? '',
            ]);

            if ($params['status'] == UserSlaughterRecordsModel::STATUS_YES) {
                // 更新认养记录状态
                $this->getUserSponsorModel()->updateItemById($slaughterRecords['user_sponsor_id'], [
                    'status' => UserSponsorModel::STATUS_RECYCLED,
                ]);
            }
        });
    }

    /**
     * 宰杀寄回
     * @return void
     * @throws Exception
     */
    public function sendBack(array $params)
    {
        // 查询审批记录
        $slaughterRecords = $this->getUserSlaughterRecordsModel()->getItemById($params['id'], [
            'id', 'user_id',
        ]);
        if (empty($slaughterRecords)) {
            throw new SponsorException('用户申请记录不存在', SponsorException::CODE_5001);
        }

        $createSlaughterExpressRecords = [
            'express_company_code' => $params['expressCompanyCode'],
            'express_no' => $params['expressNo'],
            'remark' => $params['remark'] ?? '',
        ];

        $createSlaughterSendBackRecords = [
            'user_slaughter_records_id' => $slaughterRecords['id'],
            'slaughter_express_id' => 0,
        ];

        DB::transaction(function () use ($slaughterRecords, $createSlaughterExpressRecords, $createSlaughterSendBackRecords) {
            // 添加宰杀寄回快递表
            $expressId = $this->getSlaughterExpressModel()->addItemGetId($createSlaughterExpressRecords);
            // 添加宰杀回购记录
            $createSlaughterSendBackRecords['slaughter_express_id'] = $expressId;
            $this->getSlaughterSendBackRecordsModel()->addItem($createSlaughterSendBackRecords);
        });
    }

    /**
     * 发放积分
     * @param array $params
     * @return void
     * @throws SponsorException
     * @throws Exception
     */
    public function grantIntegral(array $params)
    {
        // 查询审批记录
        $slaughterRecords = $this->getUserSlaughterRecordsModel()->getItemById($params['id'], [
            'id', 'user_id'
        ]);
        if (empty($slaughterRecords)) {
            throw new SponsorException('用户申请记录不存在', SponsorException::CODE_5001);
        }

        $createUserIntegralRecords = [
            'user_id' => $slaughterRecords['user_id'],
            'type' => UserIntegralRecordsModel::TYPE_INCREMENT,
            'source_type' => UserIntegralRecordsModel::SOURCE_TYPE_SLAUGHTER,
            'source_id' => $params['id'],
            'quantity' => $params['quantity'],
            'remark' => $params['remark'] ?? '',
        ];

        $createSlaughterIntegralRecords = [
            'user_slaughter_records_id' => $slaughterRecords['id'],
        ];

        DB::transaction(function () use ($slaughterRecords, $createUserIntegralRecords, $createSlaughterIntegralRecords) {
            // 添加用户积分
            $this->getUserModel()->updateItemById($createUserIntegralRecords['user_id'], [
                'integral' => DB::raw('integral + ' . $createUserIntegralRecords['quantity'])
            ]);
            // 添加用户积分记录
            $integralRecordsId = $this->getUserIntegralRecordsModel()->addItemGetId($createUserIntegralRecords);
            // 添加宰杀积分记录
            $createSlaughterIntegralRecords['user_integral_records_id'] = $integralRecordsId;
            $this->getSlaughterIntegralRecordsModel()->addItem($createSlaughterIntegralRecords);
        });
    }
}
